#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <unistd.h>
#include <stdbool.h>

char* word_extract(const char* origin_buf);
char* descrip_extract(const char* origin_buf);
char* pronounce_extract(const char* origin_buf);
bool isThereHasSlash(const char* origin_buf);

void get_db_name(char* db_name,char* txt_name)
{
	int choice = 0;

	printf("1.words.txt add to words.db\n2.read_words.txt add to reading_material_words.db\n");
	printf("which words data bank would you prefer to add words?");
	scanf("%d",&choice);
	getchar();

	if(1 == choice){
		strcpy(db_name,"words.db");
        strcpy(txt_name,"words.txt");
	}else{
		strcpy(db_name,"reading_material_words.db");
        strcpy(txt_name,"read_words.txt");
	}

	return;
}


int main(int argc, char *argv[])
{
	sqlite3 *db;
    char db_name_buf[50] = {0};
    char txt_name_buf[50] = {0};

    get_db_name(db_name_buf,txt_name_buf);

	FILE *fp = fopen(txt_name_buf, "r+");
	if( NULL == fp ){
		perror("fopen");
		return -1;
	}
    if( SQLITE_OK != sqlite3_open(db_name_buf, &db) ){
		sqlite3_errmsg(db);
		return -1;
	}

	int count= 0;
	int i = 0;
	char *p;
	char *errmsg;
	char words[32], description[1024],m_pronounce[1024];
    char c_test[] = "你好，我是中文";
    char c1_test[] = {-28,-67,-96,-27,-91,-67,-17,-68,-116,-26,-120,-111,-26,-104,-81,-28,-72,-83,-26,-106,-121,0};
	char buf[2048];
	char sql[1024];
	printf("换行键：0x%x,dec:%d\n 空格:dec:%d,斜杠：dec:%d.\n",'\n','\n',' ','/');
    printf("%s\n",c_test);
    for(i = 0; i < 23;i++){
        printf("%d,",c_test[i]);
    }
    printf("\n");
    printf("c1_test:%s\n",c1_test);


	char **result;
	int nrow, ncloumn;
    char max_id[10];
    bzero(sql, sizeof(sql));
    //如果表项中已有记录，则id从最大的id+1开始写入，否则从1开始写入
    sprintf(sql, "SELECT max(id) FROM wordslist");
	if(sqlite3_get_table(db, sql, &result, &nrow, &ncloumn, &errmsg) != SQLITE_OK){
		printf("err:%s\n", errmsg);
		return -1;
	}else{
        if(NULL == result[1]){
            printf("NULL\n");
            i = 1;
        }else{
            strcpy(max_id,result[1]);
            i = atoi(max_id);
            i += 1;
        }
	}

    while( fgets(buf, sizeof(buf), fp) != NULL ){
        // printf("单词:[%s]                           ",word_extract(buf));
        // printf("词义:[%s]                ",descrip_extract(buf));
        // printf("音标:[%s]",pronounce_extract(buf));
        // memset(buf,0,1024);
        // printf("\n");
        bzero(sql, sizeof(sql));
		sprintf(sql, "insert into wordslist values(%d, \"%s\", \"%s\", \"%s\", 0, 0)", i,word_extract(buf),descrip_extract(buf),pronounce_extract(buf));
        
        count++;
		if( SQLITE_OK != sqlite3_exec(db, sql, NULL, NULL, &errmsg) ){
			printf("err : %s\n", errmsg);
			printf("count = %d\n", count);
		}
        i++;
    }

    if(SQLITE_OK != sqlite3_close(db)){
		printf("数据库关闭失败\n");
	}else
		printf("success append %d words in %s\n",count,db_name_buf);
    
    fclose(fp);
    
    return 0;
}


char* word_extract(const char* origin_buf)
{
    int i = 0;
    static char word[50] = {0};
    memset(word,0,50);
    //提取单词
    while((origin_buf[i] >= 'A' && origin_buf[i] <= 'Z') || (origin_buf[i] >= 'a' && origin_buf[i] <= 'z') || (origin_buf[i] == '-')){
            word[i] = origin_buf[i];
            i++;
            //防止因为逻辑失误导致一直跳不出while循环
            if(i > 100){
                printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                break;
            } 
    }
    
    return word;
}

char* descrip_extract(const char* origin_buf)
{
    int i = 0,j = 0,length = 0;
    static char descrip[300] = {0};
    memset(descrip,0,300);
    //跳过单词部分
    while((origin_buf[i] >= 'A' && origin_buf[i] <= 'Z') || (origin_buf[i] >= 'a' && origin_buf[i] <= 'z') || (origin_buf[i] == '-')){
        i++;
        //防止因为逻辑失误导致一直跳不出while循环
        if(i > 100){
            printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
            break;
        } 
    }

    //跳过单词与词义之间的空白
    while(origin_buf[i] == ' ' || origin_buf[i] == 9){
        //printf("jump space and TAB charactor,dec:%d hex:0x%x.\n",origin_buf[i],origin_buf[i]);
        i++;
        if(i > 200){
            printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
            break;
        } 
    }

    //提取词义
    while(origin_buf[i] != ' ' &&  origin_buf[i] != 9){
        if(origin_buf[i] == 0){
            //只有词义并且立马回车了
            if(strlen(descrip) > 0 && !isThereHasSlash(descrip)){
                break;
            }else{
                printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                return NULL;
            }
        }
        //printf("%d ",origin_buf[i]);
        descrip[j] = origin_buf[i];
        i++;
        j++;
        if(i > 400){
            printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
            break;
        } 
    }
    //词义中间夹杂了一个空格来区分不同词性的情况
    if(origin_buf[i+1] != ' ' && origin_buf[i+1] != '/' && origin_buf[i+1] != 0 && origin_buf[i+1] != 10 && origin_buf[i+1] != 13 && origin_buf[i+1] != '\t'){
        descrip[j] = origin_buf[i];
        i++;
        j++;
        //提取词义
        while(origin_buf[i] != ' ' &&  origin_buf[i] != 9){
            if(origin_buf[i] == 0){
                //只有词义并且立马回车了
                if(strlen(descrip) > 0 && !isThereHasSlash(descrip)){
                    break;
                }else{
                    printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                    return NULL;
                }
            }
            //printf("%d ",origin_buf[i]);
            descrip[j] = origin_buf[i];
            i++;
            j++;
            if(i > 400){
                printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                break;
            } 
        }
    }

    //吃掉换行符
    length = strlen(descrip);
    for(i = 0; i < length; i++){
        if(descrip[i] == 13 || descrip[i] == 10){
            descrip[i] = 0;
        }
    }
    
    return descrip;
}


char* pronounce_extract(const char* origin_buf)
{
    int i = 0,j = 0,length = 0;
    static char pronounce[200] = {0};
    memset(pronounce,0,200);
    while(origin_buf[i] != '/'){
        i++;
        if(origin_buf[i] == '\n' || origin_buf[i] == 0){
            //printf("this line has no pronounce.func:%s line:%d.",__func__,__LINE__);
            pronounce[0] = '/';
            goto end;
        }
        if(i > 500){
            printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
            return NULL;
        } 
    }
    //有时候会遇到词义中包含斜杠的情况，那就再往后推一次
    if(origin_buf[i+1] != ' ' && origin_buf[i+1] != 0 && origin_buf[i+1] != 10 && origin_buf[i+1] != 13){
        i++;
        while(origin_buf[i] != '/'){
            i++;
            if(origin_buf[i] == '\n' || origin_buf[i] == 0){
                //printf("this line has no pronounce.func:%s line:%d.",__func__,__LINE__);
                pronounce[0] = '/';
                goto end;
            }
            if(i > 500){
                printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                return NULL;
            } 
        }
    }

    //有时候会遇到词义中包含斜杠的情况，那就再往后推一次
    if(origin_buf[i+1] != ' ' && origin_buf[i+1] != 0 && origin_buf[i+1] != 10 && origin_buf[i+1] != 13){
        i++;
        while(origin_buf[i] != '/'){
            i++;
            if(origin_buf[i] == '\n' || origin_buf[i] == 0){
                //printf("this line has no pronounce.func:%s line:%d.",__func__,__LINE__);
                pronounce[0] = '/';
                goto end;
            }
            if(i > 500){
                printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
                return NULL;
            } 
        }
    }

    while(origin_buf[i] != 0){
        pronounce[j] = origin_buf[i];
        i++;j++;
        if(i > 500){
            printf("logic err!　now break out from while circle. func:%s line:%d.\n",__func__,__LINE__);
            return NULL;
        } 
    }
    //吃掉换行符
    length = strlen(pronounce);
    for(i = 0; i < length; i++){
        if(pronounce[i] == 13 || pronounce[i] == 10){
            pronounce[i] = 0;
        }
    }
end:
    

    return pronounce;
}

bool isThereHasSlash(const char* origin_buf)
{
    int i;
    int length = strlen(origin_buf);
    for(i = 0; i < length;i++){
        if(origin_buf[i] == '/') return true;
    }

    return false;
}